/**
 * @description 让图片撑满容器 又不留空白 不拉伸变形不失真
 * @directive v-crop
 * @param Object
 * @example v-crop="{width: Number容器宽度, height: Number容器高度, src: String图片路径, defaultSrc: String默认图片路径, unit: 'rem' or 'px'宽高单位}"
 *    defaultSrc请用网络图片  相对路径解析会出错 (图片未加入静态资源)
* */
const Crop = {};
Crop.install = function(Vue, options){
	Vue.directive('crop', {
    bind: function (el, binding, vnode, oldVnode) {
      //定义变量
      let ratio = binding.value.width / binding.value.height,//容器宽高比
        scale = 0, fullWidth = 0, fullHeight = 0, offsetX = 0, offsetY = 0,//图片缩放比例  实际宽高  xy轴偏移量
        unit = binding.value.unit || 'px',//单位, 默认px   可选rem
        rem = parseFloat(document.getElementsByTagName('html')[0].style.fontSize),//rem基础值  根节点fontSize
        img = document.createElement('img'), defaultImg = document.createElement('img');//创建图片
      //设置图片容器样式属性
      el.style.display = 'inline-block';
      el.style.position = 'relative';
      el.style.width = binding.value.width + unit;
      el.style.height = binding.value.height + unit;
      el.style.overflow = 'hidden';
      //加载图片
      img.src = binding.value.src;
      img.onload = function (e) {
        //计算图片的实际宽高
        if (unit === 'rem') {
          fullWidth = img.width / rem;
          fullHeight = img.height / rem;
        } else if (unit === 'px') {
          fullHeight = img.height;
          fullWidth = img.width;
        }
        if (fullWidth / fullHeight > ratio) {
          //图片比较宽  图片缩放比例按高度算
          //图片放大倍数
          scale = binding.value.height / img.height;
          //x轴偏移
          offsetX = -(img.width * scale - binding.value.width) / 2;
        } else {//图片比较窄  图片缩放比例按宽度算
          //图片放大倍数
          scale = binding.value.width / img.width;
          //y轴偏移
          offsetY = -(img.height * scale - binding.value.height) / 2;
        }
        //根据缩放比例 偏移量  设置图片属性
        img.style.width = img.width * scale + unit;
        img.style.height = img.height * scale + unit;
        img.style.position = 'absolute';
        img.style.left = offsetX + unit;
        img.style.top = offsetY + unit;
        el.appendChild(img);
      };
      //可以穿一个默认图片  资源加载出错后加载默认图片
      img.onerror = function (e) {
        if (binding.value.defaultSrc) {
          defaultImg.src = binding.value.defaultSrc;
          defaultImg.style.position = 'absolute';
          defaultImg.style.top = 0;
          defaultImg.style.bottom = 0;
          defaultImg.style.left = 0;
          defaultImg.style.right = 0;
          defaultImg.style.margin = 'auto';
          el.appendChild(defaultImg);
        } else {
          el.appendChild(img);
        }
      }
    }
  })
};
export default Crop;
